import { useEffect, useState } from "react";
import {
    useAccount,
    useWaitForTransactionReceipt,
    useWriteContract,
} from "wagmi";
import { parseEther } from "viem";
import { miningContract } from "../../provider/Contract";
import { useConnectModal } from "@rainbow-me/rainbowkit";
import Big from "big.js";
import type { PoolType } from "../../types";

interface Props {
    pool: PoolType;
    refetch: () => void;
}

const Pool = ({ pool, refetch }: Props) => {
    const { address } = useAccount();
    const { openConnectModal } = useConnectModal();
    const [error, setError] = useState<string | null>(null);
    const [txStatus, setTxStatus] = useState<string | null>(null);
    const [stakeAmount, setStakeAmount] = useState<string>("0.0001");

    const multiplier = new Big("1e18");
    const {
        writeContract,
        data: txHash,
        isPending,
        error: writeError,
    } = useWriteContract();
    const {
        isSuccess: isTxConfirmed,
        isLoading: isTxLoading,
        isError: isTxError,
        error: txError,
    } = useWaitForTransactionReceipt({
        hash: txHash,
        query: {
            enabled: !!txHash,
        },
    });

    useEffect(() => {
        if (isTxConfirmed) {
            setTxStatus("交易确认成功！");
            refetch();
        }
        if (isTxError && txError) {
            setError("交易失败：" + txError.message);
        }
        if (writeError) {
            setError("交易失败：" + writeError.message);
        }
    }, [isTxConfirmed, isTxError, txError, writeError, refetch]);

    const staking = (pool: PoolType) => {
        try {
            if (!address) {
                openConnectModal?.();
                return;
            }
            if (
                !pool.miningId ||
                !pool.tokenAddress ||
                pool.total === undefined
            ) {
                throw new Error("无效的池数据");
            }
            if (
                !stakeAmount ||
                isNaN(Number(stakeAmount)) ||
                Number(stakeAmount) <= 0
            ) {
                throw new Error("无效的质押金额");
            }

            const val = new Big(stakeAmount).times(multiplier).toString();
            const commonArgs = [pool.miningId];
            const isTokenStaking = pool.symbol !== "BNB";

            if (isTokenStaking) {
                writeContract({
                    ...miningContract,
                    functionName: "stakingToken",
                    args: [...commonArgs, pool.tokenAddress, val],
                    gas: 300000n,
                });
            } else {
                writeContract({
                    ...miningContract,
                    functionName: "stakingBNB",
                    args: commonArgs,
                    value: parseEther(stakeAmount),
                    gas: 300000n,
                });
            }
        } catch (error) {
            setError("质押失败：" + (error as Error).message);
        }
    };

    return (
        <div
            style={{
                border: "1px solid #e0e0e0",
                borderRadius: "8px",
                padding: "16px",
                margin: "16px 0",
                backgroundColor: "#fff",
                boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
                maxWidth: "400px",
                fontFamily: "Arial, sans-serif",
            }}
        >
            {/* 状态提示 */}
            {error && (
                <div
                    style={{
                        color: "#d32f2f",
                        backgroundColor: "#ffebee",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    {error}
                </div>
            )}
            {txStatus && (
                <div
                    style={{
                        color: "#2e7d32",
                        backgroundColor: "#e8f5e9",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    {txStatus}
                </div>
            )}
            {isTxLoading && (
                <div
                    style={{
                        color: "#0288d1",
                        backgroundColor: "#e3f2fd",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    交易处理中...
                </div>
            )}
            {isPending && (
                <div
                    style={{
                        color: "#0288d1",
                        backgroundColor: "#e3f2fd",
                        padding: "8px",
                        borderRadius: "4px",
                        marginBottom: "12px",
                        fontSize: "14px",
                    }}
                >
                    等待钱包确认...
                </div>
            )}
            {txHash && (
                <div
                    style={{
                        color: "#424242",
                        fontSize: "12px",
                        wordBreak: "break-all",
                        marginBottom: "12px",
                    }}
                >
                    交易哈希: {txHash}
                </div>
            )}

            {/* 池信息 */}
            <div
                style={{
                    display: "grid",
                    gridTemplateColumns: "1fr 2fr",
                    gap: "8px",
                    marginBottom: "16px",
                }}
            >
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    Mining ID:
                </span>
                <span>{pool.miningId}</span>
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    Symbol:
                </span>
                <span>{pool.symbol}</span>
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    Total:
                </span>
                <span>{pool.total}</span>
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    Staking Num:
                </span>
                <span>{pool.stakingNum}</span>
                <span style={{ fontWeight: "bold", color: "#424242" }}>
                    Rate:
                </span>
                <span>{pool.rate}</span>
            </div>

            {/* 输入框和按钮 */}
            <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
                <input
                    type="number"
                    value={stakeAmount}
                    onChange={(e) => setStakeAmount(e.target.value)}
                    placeholder="输入质押金额"
                    disabled={!address || isPending || isTxLoading}
                    style={{
                        padding: "8px",
                        border: "1px solid #e0e0e0",
                        borderRadius: "4px",
                        fontSize: "14px",
                        width: "100%",
                        outline: "none",
                        transition: "border-color 0.2s",
                    }}
                    onFocus={(e) => (e.target.style.borderColor = "#1976d2")}
                    onBlur={(e) => (e.target.style.borderColor = "#e0e0e0")}
                />
                <button
                    disabled={isPending || isTxLoading}
                    onClick={() => staking(pool)}
                    style={{
                        padding: "8px 16px",
                        backgroundColor:
                            address && !isPending && !isTxLoading
                                ? "#1976d2"
                                : "#bdbdbd",
                        color: "#fff",
                        border: "none",
                        borderRadius: "4px",
                        cursor:
                            address && !isPending && !isTxLoading
                                ? "pointer"
                                : "not-allowed",
                        fontSize: "14px",
                        transition: "background-color 0.2s",
                    }}
                    onMouseOver={(e) =>
                        address && !isPending && !isTxLoading
                            ? (e.currentTarget.style.backgroundColor =
                                  "#1565c0")
                            : null
                    }
                    onMouseOut={(e) =>
                        address && !isPending && !isTxLoading
                            ? (e.currentTarget.style.backgroundColor =
                                  "#1976d2")
                            : null
                    }
                >
                    {address ? "质押" : "连接钱包以质押"}
                </button>
            </div>
        </div>
    );
};

export default Pool;
